package com.ijiuchuang.jc_localization.ble;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothManager;
import android.content.Context;

import com.ijiuchuang.jc_localization.tools.utils.Log;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;

/**
 * Created by Veev on 2016/7/6
 *
 * @link 384506557@qq.com
 */
public class BleUtil {

    private static BluetoothManager mBluetoothManager;
    // BT 适配器
    private static BluetoothAdapter mBluetoothAdapter;
    private static BluetoothGatt mBluetoothGatt;

    public static BluetoothAdapter getBluetoothAdapter() {
        return mBluetoothAdapter;
    }

    public static BluetoothManager getmBluetoothManager() {
        return mBluetoothManager;
    }

    public static void bleInit(Context context, BleCallback.BleInitListener listener) {
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                // Unable to initialize BluetoothManager.
                listener.onFailure();
                return;
            }
        }

        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            // Unable to obtain a BluetoothAdapter.
            listener.onFailure();
            return;
        }

        if (!mBluetoothAdapter.isEnabled()) {
            listener.onDisEnabled();
            return;
        }

        listener.onSuccess();
    }

    public static void startScan(long time, final BluetoothAdapter.LeScanCallback callback) {
        mBluetoothAdapter.startLeScan(callback);
        Observable.timer(time, TimeUnit.MILLISECONDS)
                .subscribe(new Subscriber<Long>() {
                    @Override
                    public void onCompleted() {
                        Log.i("onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(Long aLong) {
                        Log.i("onNext");
                        mBluetoothAdapter.stopLeScan(callback);
                    }
                });
    }
}
